﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CarShop.UserInterface.Wpf.ViewModels;

namespace CarShop.UserInterface.Wpf.Windows
{
    /// <summary>
    /// Interaction logic for AuthenticationWindow.xaml
    /// </summary>
    public partial class AuthenticationWindow : Window
    {
        public AuthenticationWindow()
        {
            InitializeComponent();

            userNameTextBox.Focus();
        }


        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);

            if (e.Property.Name == "DataContext")
            {
                var viewModel = this.DataContext as AuthenticationWindowViewModel;

                if (viewModel != null)
                {
                    viewModel.Password = passwordBox.Password;
                }
            }
        }



        private void TryLogIn()
        {
            var viewModel = this.DataContext as AuthenticationWindowViewModel;

            if (viewModel != null && viewModel.LogInCommand.CanExecute(null))
            {
                viewModel.LogInCommand.Execute(null);
            }
        }



        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
        {
            var viewModel = this.DataContext as AuthenticationWindowViewModel;

            if (viewModel != null)
            {
                viewModel.Password = passwordBox.Password;
            }
        }

        private void UserNameTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.TryLogIn();
            }
        }

        private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this.TryLogIn();
            }
        }
    }
}
